package com.lagou.server;

import org.I0Itec.zkclient.ZkClient;

import java.util.Timer;

public class TimeTask {
    private static boolean ifCalled = false;

    public static void doCleanTime(){
        Timer timer = new Timer();
        timer.schedule(new MyTask(), 1000, 5000);//在1秒后执行此任务,每次间隔2秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.
        /*while(true) {//这个是用来停止此任务的,否则就一直循环执行此任务了
            try {
                int ch = System.in.read();
                if(ch-'c'==0) {
                    timer.cancel();//使用这个方法退出任务
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    }




    static class MyTask extends java.util.TimerTask{
        @Override
        public void run() {
            if (!ifCalled){
                System.out.println("清空响应时间");//你要进行的操作
                ZkClient zkClient = new ZkClient("127.0.0.1:2181");
                // 判断节点是否存在
                String path = "/zkServer2-actTime";
                boolean exist = zkClient.exists(path);

                if (exist){
                    zkClient.writeData(path,"0");
                }
                if(!exist){
                    // 创建临时节点
                    zkClient.createEphemeral(path,"0");
                }
            }

        }
    }

    public static boolean isIfCalled() {
        return ifCalled;
    }

    public static void setIfCalled(boolean ifCalled) {
        TimeTask.ifCalled = ifCalled;
    }

    public static void main(String[] args){
        doCleanTime();
    }
}
